import { useEffect,useRef,useState } from "react"
const useList = <T = any>(option: {
    request: (pageIndex: number,pageSize: number,params?: any) => Promise<{
        data: T[];
        total: number;
    }>;
    default_page_size: number;
}) => {
    const [list,setList] = useState<T[]>([])
    const [total,setTotal] = useState(0);
    const curr_page = useRef(1);
    const isReset = useRef(false);
    const page_size = useRef(option.default_page_size)
    const getList = async(
        _option?: {
            params?: any;
            old_data?: T[];
        }) => {
        _option = _option || {};
        let _params = { ..._option.params };
        const res = await option.request(curr_page.current,page_size.current,_params);
        let old_data = _option.old_data || [];
        setList([...old_data,...res.data]);
        setTotal(res.total);
    }
    const onReset = () => {
        curr_page.current = 1;
        isReset.current = true;
        setTotal(0);
        setList([])
    }
    const onSearch = () => {
        onReset();
    }
    useEffect(() => {
        if (list.length === 0 && curr_page.current === 1 && isReset.current) {
            getList({
                old_data: [],
            });
            isReset.current = false;
        }
    },[list,curr_page.current,isReset.current])
    const onPageScrollToLower = () => {
        const totalPage = parseInt((((total || 0) + 20 - 1) / 20).toString());
        if (totalPage <= 1) {
            return;
        }
        if (curr_page.current < totalPage) {
            curr_page.current = curr_page.current + 1;
            getList({
                old_data: list,
            })
        }
    }
    return {
        list,
        total,
        curr_page,
        page_size,
        getList,
        onSearch,
        onReset,
        /**滚动到底部/右边，会触发 */
        onPageScrollToLower,
    }
}

export default useList